#/bin/python
#coding:utf8
'''
Created on 2011-4-29

@author: mark
'''

import config
import web

mc = config.memcache_client
db = config.database


def cleanCache(uid):
    key = str("user_%d" % uid)
    mc.delete(key)
    
def getuserbyid(uid):
    key = str("user_%s" % uid)
    user = mc.get(key)
    if not user:
        user = _getuserbyid(uid)
        if user:
            mc.set(key, user, config.cache_timeout)
    return user
    
def _getuserbyid(uid):
    results = db.select('user', where='uid =%s' % uid)
    if results:
        return results[0]

def getuserbymailandpass(email, passwd):
    results = db.query("SELECT * FROM user WHERE email=$email and passwd=$passwd", vars={'email':email, 'passwd':passwd})
    if results:
        return results[0]

def createuser(_email, _passwd,_nickname):
    uid = db.insert('user', email=_email, passwd=_passwd,nickname= _nickname,createdate = web.SQLLiteral("NOW()"),image = config.defaut_logo)
    return uid

def checkemail(email):
    result = db.query("SELECT * FROM user WHERE email=$email", vars={'email':email})
    return result

def updatellt(uid):
    cleanCache(uid)
    db.update("user", where="uid=%s" % uid, llt=web.SQLLiteral("NOW()"))
    return True

def updatepasswd(uid, passwd):
    cleanCache(uid)
    db.update("user", where="uid=%s" % uid , passwd=passwd)
    return True;

def updatelogo(uid, image):
    cleanCache(uid)
    db.update("user", where="uid = %s" % uid , image=image)
    return True

def updateUserInfo(uid, nickname,district, cellphone):
    cleanCache(uid)
    db.update("user", where="uid = %s" % uid , nickname=nickname, district=district,cellphone=cellphone)
    return True
